import pymysql
from setting import DB_INFO
from loguru import logger


# 实现连接数据库操作
class BaseMysql:

    # 创建连接对象
    def __init__(self):
        self.conn = pymysql.connect(**DB_INFO)

    # 执行SQL语句，主要处理增删改
    def execute(self,sql):
        try:
            with self.conn.cursor() as cursor:
                logger.info("执行的SQL语句为:{}".format(sql))
                cursor.execute(sql)
                self.conn.commit()      # 事务提交
        except Exception as e:
            logger.error("执行SQL异常:{}".format(e))
            self.conn.rollback()

    # 执行sql语句 ，进行查询
    def get_data(self,sql):
        try:
            with self.conn.cursor() as cursor:
                logger.info("执行的查询语句为:{}".format(sql))
                cursor.execute(sql)
                result = cursor.fetchall()
                return result
        except Exception as e:
            logger.error("执行SQL异常:{}".format(e))

    def close(self):
        self.conn.close()
